import axios from "axios";
import { getToken, removeToken } from "./cookie";
import router from "@/router";

// 不同的功能，通过axios请求的是不同接口地址
const service = axios.create({
    baseURL: "/dev-api",
    timeout: 20000,
    withCredentials: true  // 允许跨域携带cookie
})

// 需要认证的操作方法列表（更精确匹配）
const writeMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];

// 检查当前请求是否是写操作
const isWriteOperation = (config) => {
    return writeMethods.includes(config.method?.toUpperCase());
}

// 响应拦截器优化版
service.interceptors.response.use(
    (res) => {
        const { code = 1000, msg } = res.data;

        if (code === 3001) { // token过期
            if (isWriteOperation(res.config)) {
                removeToken();
                ElMessage.warning("请登录后继续操作");
            }
            return Promise.reject(msg);
        }

        return code === 1000 ? res.data : Promise.reject(msg);
    },
    (error) => {
        const message = error.message === "Network Error"
            ? "网络连接异常"
            : error.message.includes("timeout")
                ? "请求超时"
                : "服务异常";
        ElMessage.error(message);
        return Promise.reject(error);
    }
);

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        if (getToken()) {
            config.headers["Authorization"] = "Bearer " + getToken();
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default service